/*
 * @brief:    使用消息队列实现简单的裸机任务调度
 * @author:   guangjieMVP
 * @date:     2020-12-25
 * @version:  v1.0.0
 * @  copyright(c) 2020: OptoMedic Technologies Co.,Ltd. All rights reserved
 */

#include "msgevent.h"
#include "stdio.h"

void MQ_Lock_Take(void);
void MQ_Lock_Release(void);

/**
 * @brief:        判斷環形隊列是否空
 * @param[in]:     None
 * @retval[out]:   None
 * @author:       AresXu
 * @version:      v1.0.0
 */
static uint8_t IsMsgQueueEmpty(stMsgQueue *mq)
{
    if (mq->in == mq->out)
    {
		printf("queue is empty\r\n");
        return 1;
    }
    return 0;
}

/**
 * @brief:         判斷環形隊列是否满
 * @param[in]:     None
 * @retval[out]:   None
 * @note:
 * @author:       AresXu
 * @version:      v1.0.0
 */
static uint8_t IsMsgQueueFull(stMsgQueue *mq)
{
    if (((mq->in + 1) % MSG_QUEUE_SIZE) == mq->out)
    {
    	printf("queue is full\r\n");
        return 1;
    }

    return 0;
}

uint8_t MQ_PublishMsg(stMsgQueue *mq, MsgType msg)
{
     /* lock */
    MQ_Lock_Take();

    if (IsMsgQueueFull(mq) == 1) //队列满不能写入消息
    {
        return 0;
    }

    mq->buf[mq->in] = msg;
    mq->in = (++mq->in) % MSG_QUEUE_SIZE; //防止越界
	 printf("in %d %d\r\n", mq->in, __LINE__);
     /* unlock */
    MQ_Lock_Release();

    return 1;
}

/* 发送紧急消息 */
int8_t MQ_PublishUrgentMsg(stMsgQueue *mq, MsgType msg)
{
     /* lock */
    MQ_Lock_Take();

    if (IsMsgQueueFull(mq) == 1) //队列满不能写入消息
    {
        return -1;
    }

    if (mq->out == 0)
    {
 //   	printf("out is 0, %d\r\n", __LINE__);
        mq->buf[MSG_QUEUE_SIZE - 1] = msg;
        mq->out = MSG_QUEUE_SIZE - 1;
 //       printf("out %d %d\r\n", mq->out, __LINE__);
    }
    else
    {
        mq->out = (--mq->out) % MSG_QUEUE_SIZE; //防止越界
        mq->buf[mq->out] = msg;
//		printf("out %d %d\r\n", mq->out, __LINE__);
    }
      /* unlock */
    MQ_Lock_Release();

    return 1;
}

uint8_t MQ_GetMsg(stMsgQueue *mq, MsgType *msg)
{
    /* lock */
    MQ_Lock_Take();

    if (IsMsgQueueEmpty(mq))
    {
        return 0;
    }

    *msg = mq->buf[mq->out];
    mq->out = (++mq->out) % MSG_QUEUE_SIZE; //防止越界
//	printf("out %d %d\r\n", mq->out, __LINE__);
    /* unlock */
    MQ_Lock_Release();

    return 1;
}

// //主函数循环调用
// void MsgQueue_HandleLoop(stMsgQueue *mqHead)
// {
// 	msg_node_t *msg;
// 	while( (msg = get_messge(mqHead)) != NULL )
// 	{
// 		if (msg->handler != NULL)
// 			msg->handler(msg->parm);
// 	}
// }
